package com.pw.ba.base.controller;


import com.pw.ba.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/seckill")
@Slf4j
public class SeckillController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    Redisson redisson;

    @PostMapping("/redistest")
    public String redisTest(String goodName) {
        //纯redis的分布式锁
        String lockKey = "lockKey";
        /*String clientId = UUID.randomUUID().toString();*/

        RLock redissonLock = redisson.getLock(lockKey);


        try {
            //纯redis的分布式锁
            /*Boolean result = redisUtil.setnx("lockKey", "lock", 10 , TimeUnit.SECONDS);
            if (!result){
                return "error_code";
            }*/
            //redisson的分布式锁
            redissonLock.lock();
            int stock = (int) redisUtil.get(goodName);
            if (stock > 0) {
                int realStock = stock - 1;
                redisUtil.set(goodName, realStock);
                log.info("扣减成功，剩余库存：" + realStock);
            } else {
                log.info("扣减失败，库存不足");
            }
        } finally {
            //纯redis的分布式锁
            /*if (clientId.equals(redisUtil.get(lockKey))){
                redisUtil.del(lockKey);
            }*/
            //redisson的分布式锁
            redissonLock.unlock();
        }


        return "success";

    }

}
